/**
 * @fileoverview
 * 待办卡片：1 - 5
 */

import { ReactNode } from "react";
import Taro from "@tarojs/taro";
import { Text, View } from "@tarojs/components";

import Moment from "./Moment";
import ByCol from "../ui/ByCol";
import ByRow from "../ui/ByRow";
import UserItem from "./UserItem";
import ByText from "../ui/ByText";
import ByButton from "../ui/ByButton";
import ProgressItem from "./ProgressItem";
import TodoApproveCard from "./TodoApproveCard";

import { objectToQueryString } from "@/utils";
import { request } from "@/utils/request";
import ApiFinance from "@/api/finance";

type BaseCardProps = {
  pure?: boolean;
  source: any;
  children?: React.ReactNode;
  slotTitleRight?: ReactNode;

  onClick?: (event?: any) => void;
};

const BaseCard = ({
  pure,
  source,
  children,
  slotTitleRight,
  onClick,
}: BaseCardProps) => {
  return (
    <View
      className="mb-3 p-4 bg-white rounded-2xl shadow-black-1"
      onClick={onClick}
    >
      <ByRow>
        <ByCol span={"auto"}>
          <ByText bold size="xl">
            {source.title}
          </ByText>
        </ByCol>
        <ByCol span={"none"}>{slotTitleRight}</ByCol>
      </ByRow>

      {!pure && (
        <View className="flex justify-bewteen my-3">
          <View className="flex-1">
            <Text>{source.customerName}</Text>
          </View>
          <View className="flex-1 text-second text-sm text-right">
            {source.customerAddress}
          </View>
        </View>
      )}

      {children}

      <ByRow className="mt-3" align="center">
        {/* <UserItem name={source.createUserName} size={54} /> */}

        <Moment
          className="text-second text-sm"
          value={source.startTime}
          type="full"
        />
      </ByRow>
    </View>
  );
};

/**
 * 待办 工人工费申请卡片
 * itemType = 4
 * @returns
 */
export const TodoFeesCard = ({ pure, source }: BaseCardProps) => {
  const {
    id,
    intentCustomerId,
    business_data: {
      workType,
      constructionProjectName,
      workFlowDefinitionCode,
    },
  } = source;

  const query = {
    workerType:workType,
    intentCustomerId,
    constructionProjectName,
    wlCode: workFlowDefinitionCode,
    wl_id: id,
  };

  return (
    <BaseCard source={source} pure={pure}>
      <View className="flex justify-bewteen items-center my-3">
        <View className="flex-1">
          {/* <Text className="text-sm text-second">工人:</Text>
          <Text className="text-primary font-bold">3??</Text> */}
        </View>
        <View className="flex-1">
          <Text className="text-sm text-second">
            {source.business_data.constructionProjectName}
          </Text>
        </View>

        <View className="flex-none">
          <ByButton
            to={`/packageWork/pages/wages/apply?${objectToQueryString(query)}`}
          >
            申请
          </ByButton>
        </View>
      </View>
    </BaseCard>
  );
};

/**
 * 计划拟定
 * itemType = 1
 */
export const TodoPlanCard = ({ pure, source }: BaseCardProps) => {
  const { intentCustomerId } = source;
  return (
    <BaseCard source={source} pure={pure}>
      <ByRow content="between" align="center">
        <ByText size="sm" type="second">
          {/* 100平以内的模板 */}
        </ByText>
        <ByButton
          inlineBlock
          to={`/packageWork/pages/plan/index?intentCustomerId=${intentCustomerId}`}
        >
          拟定
        </ByButton>
      </ByRow>
    </BaseCard>
  );
};

/**
 * 待办：计划执行
 * itemType = 2
 * @param param0
 * @returns
 */
export const TodoPlanExecutionCard = ({
  pure,
  source,
  onClick,
}: BaseCardProps & { onClick?: () => void }) => {
  return (
    <BaseCard source={source} pure={pure}>
      <ByRow content="between" align="center" className="my-3">
        <View>
          {/* <Text className="text-sm text-second">已开工:</Text>
          <Text className="ml-1 text-primary font-bold text-lgF">1/10</Text> */}
        </View>
        <View>
          <ByButton onClick={onClick}>执行</ByButton>
        </View>
      </ByRow>
    </BaseCard>
  );
};

/**
 * 待办：选材
 * itemType = 3
 * @param param0
 * @returns
 */
export const TodoMaterialCard = ({ pure, source }: BaseCardProps) => {
  const {
    intentCustomerId,
    business_data: { status, chooseType },
  } = source;

  return (
    <BaseCard source={source} pure={pure}>
      <View className="flex justify-between items-center">
        <View>
          <ProgressItem
            text="选材"
            status={
              status == 2 ? "success" : status == 1 ? "active" : undefined
            }
          />
          <ProgressItem
            tail
            text="客户确认"
            status={status == 2 ? "success" : undefined}
          />
        </View>

        <View>
          <ByButton
            type="primary"
            to={`/packageProject/pages/material/index?status=${status}&intentCustomerId=${intentCustomerId}&chooseType=${chooseType}`}
          >
            选材
          </ByButton>
        </View>
      </View>
    </BaseCard>
  );
};

/**
 * 待办：派工
 * itemType = 5
 * @param param0
 * @returns
 */
export const TodoDispatchWorkerCard = ({ pure, source }: BaseCardProps) => {
  const { intentCustomerId } = source;

  return (
    <BaseCard source={source} pure={pure}>
      <View className="flex justify-bewteen items-center my-3">
        <View className="flex-1">
          {/* <Text className="text-sm text-second">待派岗位:</Text>
          <Text className="text-primary font-bold">1</Text>
          <Text className="font-bold">/3</Text> */}
        </View>

        <View className="flex-none">
          <ByButton
            to={`/packageWork/pages/dispatch/index?intentCustomerId=${intentCustomerId}`}
          >
            派工
          </ByButton>
        </View>
      </View>
    </BaseCard>
  );
};

/**
 * 项目结算
 * itemType = 7
 */
export const TodoSettlement = ({ source, ...rest }: BaseCardProps) => {
  // 结算状态 0.待确认，1.待erp确认，2.待项目经理确认，3.待付款

  const {
    intentCustomerId,
    business_data: { status },
  } = source;

  const enumBalanceStatus = {
    // 0: { label: "待申请结算", color: "info" },
    1: { label: "待erp确认", color: "warning" },
    2: { label: "待确认", color: "warning" },
    3: { label: "待付款", color: "primary" },
    4: { label: "已付款", color: "success" },
  } as const;

  // 结算状态 0.待确认，1.待erp确认，2.待项目经理确认，3.待付款

  const statusConfig = enumBalanceStatus[status];

  const navigateTo = async (event?) => {
    event?.stopPropagation();

    if (status === 0) {
      // 待结算申请且无不符合规范项
      const { confirm } = await Taro.showModal({
        title: "申请结算标准",
        content: "本项目符合结算标准，您可以提交结算申请",
        confirmText: "提交申请",
        confirmColor: "#1677ff",
      });

      if (confirm) {
        Taro.showLoading();
        await request({
          url: ApiFinance.settlementSubmit,
          data: { intentCustomerId },
        });

        Taro.showToast({ title: "操作成功" });
      }
    }

    Taro.navigateTo({
      url: `/packageProject/pages/settlement/index?intentCustomerId=${intentCustomerId}`,
    });
  };

  return (
    <BaseCard
      {...rest}
      source={source}
      slotTitleRight={
        statusConfig && (
          <ByText type={statusConfig.color}>{statusConfig.label}</ByText>
        )
      }
      onClick={navigateTo}
    >
      {/*
      <ByRow align="center">
        <ByCol span={"auto"}>
          <ByText type="second" size="sm">
            申请结算标准：<ByText type="error">1 项不符合</ByText>
          </ByText>
        </ByCol>
        <ByButton>查看</ByButton>
      </ByRow> */}


      {status === 0 ? (
        <ByRow>
          <ByCol span={"auto"}>
            <ByText type="second" size="sm">
              符合申请结算标准
              {/* 申请结算标准：<ByText type="error">1 项不符合</ByText> */}
            </ByText>
          </ByCol>
          <ByButton onClick={navigateTo}>申请结算</ByButton>
        </ByRow>
      ) : status === 1 ? (
        <ByText type="second" size="sm">
          待ERP确认
        </ByText>
      ) : (
        // 即 status == 2
        <ByRow>
          {/* <ByCol span={"auto"}>工程付款：¥3,829??</ByCol> */}
          {status === 3 && <ByButton
            to={`/packageProject/pages/engineeringFunds/apply?specialCode=fk4&intentCustomerId=${intentCustomerId}`}
          >申请付款</ByButton>}
        </ByRow>
      )}
    </BaseCard>
  );
};

/**
 * 巡检整改
 * itemType = 0
 * @returns
 */
const TodoRectification = ({ source }: BaseCardProps) => {
  // 有不合格的状态、通过、驳回
  const { intentCustomerId, business_data } = source;

  return (
    <>
      <BaseCard source={source}>
        <ByRow>
          <ByCol span={"auto"}>
            {/* xxx<ByText type="error">不合格</ByText> */}
          </ByCol>
          <ByButton
            to={`/packageProject/pages/inspection/rectificationDetail?intentCustomerId=${intentCustomerId}&rectificationId=${business_data.rectificationId}`}
          >
            整改
          </ByButton>
        </ByRow>
      </BaseCard>
    </>
  );
};

/**
 * 待办卡片：1 - 5
 * @param param
 * @returns
 */
export default ({
  pure,
  source,
  onClick,
}: Omit<BaseCardProps, "slotTitleRight" | "children">) => {
  const { itemType } = source;

  if (itemType == 6) {
    return <TodoApproveCard source={source} />;
  } else {
    const params = { pure, source };

    switch (itemType) {
      case 1:
        return <TodoPlanCard {...params} />;
      case 2:
        return <TodoPlanExecutionCard onClick={onClick} {...params} />;
      case 3:
        return <TodoMaterialCard {...params} />;
      case 4:
        return <TodoFeesCard {...params} />;
      case 5:
        return <TodoDispatchWorkerCard {...params} />;
      case 7:
        return <TodoSettlement {...params} />;
      case 8:
        return <TodoRectification {...params} />;
    }
  }
};
